<template>
  <el-dialog
    v-model="dialogVisible"
    title="报告统计"
    width="90%"
    :before-close="handleClose"
    class="report-statistics-dialog"
  >
    <div class="report-statistics">
      <!-- 统计概览 -->
      <div class="statistics-overview">
        <div class="overview-cards">
          <div class="stat-card total">
            <div class="stat-icon">
              <el-icon size="32"><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalReports }}</div>
              <div class="stat-label">总报告数</div>
            </div>
          </div>
          
          <div class="stat-card published">
            <div class="stat-icon">
              <el-icon size="32"><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ publishedReports }}</div>
              <div class="stat-label">已发布</div>
            </div>
          </div>
          
          <div class="stat-card pending">
            <div class="stat-icon">
              <el-icon size="32"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ pendingReports }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
          
          <div class="stat-card draft">
            <div class="stat-icon">
              <el-icon size="32"><Edit /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ draftReports }}</div>
              <div class="stat-label">草稿</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 报告状态分布 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>报告状态分布</span>
                  <el-button size="small" @click="refreshStatusChart">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </template>
              
              <div class="chart-container" ref="statusChartRef">
                <!-- 这里应该集成图表库，如 ECharts -->
                <div class="chart-placeholder">
                  <div class="placeholder-content">
                    <el-icon size="48"><PieChart /></el-icon>
                    <p>报告状态分布图</p>
                    <div class="chart-legend">
                      <div class="legend-item">
                        <span class="legend-color published"></span>
                        <span>已发布 ({{ publishedReports }})</span>
                      </div>
                      <div class="legend-item">
                        <span class="legend-color pending"></span>
                        <span>待审核 ({{ pendingReports }})</span>
                      </div>
                      <div class="legend-item">
                        <span class="legend-color draft"></span>
                        <span>草稿 ({{ draftReports }})</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 月度报告趋势 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>月度报告趋势</span>
                  <el-select v-model="trendPeriod" size="small" style="width: 100px">
                    <el-option label="3个月" value="3" />
                    <el-option label="6个月" value="6" />
                    <el-option label="12个月" value="12" />
                  </el-select>
                </div>
              </template>
              
              <div class="chart-container" ref="trendChartRef">
                <div class="chart-placeholder">
                  <div class="placeholder-content">
                    <el-icon size="48"><TrendCharts /></el-icon>
                    <p>月度报告趋势图</p>
                    <div class="trend-data">
                      <div v-for="(item, index) in trendData" :key="index" class="trend-item">
                        <span class="trend-month">{{ item.month }}</span>
                        <span class="trend-count">{{ item.count }}份</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px">
          <!-- 医生工作量统计 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>医生工作量统计</span>
                  <el-button size="small" @click="exportDoctorStats">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-button>
                </div>
              </template>
              
              <div class="doctor-stats">
                <div class="stats-table">
                  <div class="table-header">
                    <div class="header-cell">医生</div>
                    <div class="header-cell">报告数量</div>
                    <div class="header-cell">完成率</div>
                  </div>
                  <div class="table-body">
                    <div v-for="doctor in doctorStats" :key="doctor.id" class="table-row">
                      <div class="table-cell">
                        <div class="doctor-info">
                          <el-avatar :size="32" :src="doctor.avatar">
                            <el-icon><User /></el-icon>
                          </el-avatar>
                          <div class="doctor-details">
                            <div class="doctor-name">{{ doctor.name }}</div>
                            <div class="doctor-title">{{ doctor.title }}</div>
                          </div>
                        </div>
                      </div>
                      <div class="table-cell">
                        <div class="report-count">{{ doctor.reportCount }}</div>
                      </div>
                      <div class="table-cell">
                        <div class="completion-rate">
                          <el-progress
                            :percentage="doctor.completionRate"
                            :stroke-width="8"
                            :show-text="false"
                          />
                          <span class="rate-text">{{ doctor.completionRate }}%</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 异常指标统计 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>异常指标统计</span>
                  <el-button size="small" @click="viewAbnormalDetails">
                    <el-icon><View /></el-icon>
                    详情
                  </el-button>
                </div>
              </template>
              
              <div class="abnormal-stats">
                <div class="abnormal-overview">
                  <div class="abnormal-item high">
                    <div class="abnormal-label">偏高指标</div>
                    <div class="abnormal-count">{{ abnormalStats.high }}</div>
                  </div>
                  <div class="abnormal-item low">
                    <div class="abnormal-label">偏低指标</div>
                    <div class="abnormal-count">{{ abnormalStats.low }}</div>
                  </div>
                  <div class="abnormal-item abnormal">
                    <div class="abnormal-label">异常指标</div>
                    <div class="abnormal-count">{{ abnormalStats.abnormal }}</div>
                  </div>
                </div>
                
                <div class="abnormal-categories">
                  <h4>常见异常分类</h4>
                  <div class="category-list">
                    <div v-for="category in abnormalCategories" :key="category.name" class="category-item">
                      <div class="category-info">
                        <span class="category-name">{{ category.name }}</span>
                        <span class="category-count">{{ category.count }}例</span>
                      </div>
                      <div class="category-bar">
                        <div 
                          class="category-progress"
                          :style="{ width: category.percentage + '%' }"
                        ></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 详细数据表格 -->
      <el-card class="data-table-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>详细数据</span>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索报告"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button @click="exportData">
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table :data="filteredReportData" stripe style="width: 100%">
          <el-table-column prop="reportId" label="报告编号" width="120" />
          <el-table-column prop="patientName" label="患者姓名" width="100" />
          <el-table-column prop="checkupDate" label="体检日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.checkupDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="reportDate" label="报告日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.reportDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="primaryDoctor" label="主检医生" width="100" />
          <el-table-column prop="reviewDoctor" label="审核医生" width="100" />
          <el-table-column prop="abnormalCount" label="异常项目" width="100">
            <template #default="{ row }">
              <span :class="{ 'text-danger': row.abnormalCount > 0 }">
                {{ row.abnormalCount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewReport(row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成统计报告
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  dateRange: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:visible', 'view-report'])

// 响应式数据
const statusChartRef = ref()
const trendChartRef = ref()
const trendPeriod = ref('6')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 模拟统计数据
const totalReports = ref(1250)
const publishedReports = ref(980)
const pendingReports = ref(180)
const draftReports = ref(90)

// 趋势数据
const trendData = ref([
  { month: '1月', count: 95 },
  { month: '2月', count: 108 },
  { month: '3月', count: 125 },
  { month: '4月', count: 142 },
  { month: '5月', count: 138 },
  { month: '6月', count: 156 }
])

// 医生统计数据
const doctorStats = ref([
  {
    id: 1,
    name: '张医生',
    title: '主任医师',
    avatar: '',
    reportCount: 245,
    completionRate: 95
  },
  {
    id: 2,
    name: '李医生',
    title: '副主任医师',
    avatar: '',
    reportCount: 198,
    completionRate: 92
  },
  {
    id: 3,
    name: '王医生',
    title: '主治医师',
    avatar: '',
    reportCount: 167,
    completionRate: 88
  },
  {
    id: 4,
    name: '赵医生',
    title: '主治医师',
    avatar: '',
    reportCount: 134,
    completionRate: 90
  }
])

// 异常统计数据
const abnormalStats = reactive({
  high: 156,
  low: 89,
  abnormal: 67
})

const abnormalCategories = ref([
  { name: '血压偏高', count: 45, percentage: 80 },
  { name: '血糖异常', count: 32, percentage: 60 },
  { name: '血脂偏高', count: 28, percentage: 50 },
  { name: '肝功能异常', count: 18, percentage: 32 },
  { name: '肾功能异常', count: 12, percentage: 21 }
])

// 报告数据
const reportData = ref([
  {
    reportId: 'RPT001',
    patientName: '张三',
    checkupDate: '2024-01-15',
    reportDate: '2024-01-16',
    status: 'published',
    primaryDoctor: '张医生',
    reviewDoctor: '李医生',
    abnormalCount: 2
  },
  {
    reportId: 'RPT002',
    patientName: '李四',
    checkupDate: '2024-01-15',
    reportDate: '2024-01-17',
    status: 'pending',
    primaryDoctor: '王医生',
    reviewDoctor: '',
    abnormalCount: 0
  },
  {
    reportId: 'RPT003',
    patientName: '王五',
    checkupDate: '2024-01-16',
    reportDate: '',
    status: 'draft',
    primaryDoctor: '赵医生',
    reviewDoctor: '',
    abnormalCount: 1
  }
])

// 计算属性
const filteredReportData = computed(() => {
  if (!searchKeyword.value) {
    return reportData.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return reportData.value.filter(item => 
    item.reportId.toLowerCase().includes(keyword) ||
    item.patientName.toLowerCase().includes(keyword) ||
    item.primaryDoctor.toLowerCase().includes(keyword)
  )
})

const totalCount = computed(() => filteredReportData.value.length)

// 方法
const handleClose = () => {
  dialogVisible.value = false
}

const refreshStatusChart = () => {
  ElMessage.success('图表已刷新')
}

const exportDoctorStats = () => {
  ElMessage.info('导出医生统计数据功能开发中')
}

const viewAbnormalDetails = () => {
  ElMessage.info('查看异常详情功能开发中')
}

const exportData = () => {
  ElMessage.info('导出数据功能开发中')
}

const generateReport = () => {
  ElMessage.info('生成统计报告功能开发中')
}

const viewReport = (report) => {
  emit('view-report', report)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const getStatusType = (status) => {
  const statusMap = {
    draft: 'info',
    pending: 'warning',
    reviewed: 'primary',
    published: 'success'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    pending: '待审核',
    reviewed: '已审核',
    published: '已发布'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.report-statistics-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 85vh;
  overflow-y: auto;
}

.report-statistics {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 统计概览 */
.statistics-overview {
  margin-bottom: 20px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid;
}

.stat-card.total {
  border-left-color: #409eff;
}

.stat-card.published {
  border-left-color: #67c23a;
}

.stat-card.pending {
  border-left-color: #e6a23c;
}

.stat-card.draft {
  border-left-color: #909399;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #f0f9ff;
  color: #409eff;
}

.stat-card.published .stat-icon {
  background: #f0f9ff;
  color: #67c23a;
}

.stat-card.pending .stat-icon {
  background: #fdf6ec;
  color: #e6a23c;
}

.stat-card.draft .stat-icon {
  background: #f4f4f5;
  color: #909399;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6c757d;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #6c757d;
}

.placeholder-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.chart-legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.published {
  background: #67c23a;
}

.legend-color.pending {
  background: #e6a23c;
}

.legend-color.draft {
  background: #909399;
}

.trend-data {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  justify-content: center;
}

.trend-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  min-width: 60px;
}

.trend-month {
  font-size: 12px;
  color: #6c757d;
}

.trend-count {
  font-weight: 600;
  color: #2c3e50;
}

/* 医生统计 */
.doctor-stats {
  height: 300px;
  overflow-y: auto;
}

.stats-table {
  width: 100%;
}

.table-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1.5fr;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  color: #2c3e50;
}

.table-body {
  display: flex;
  flex-direction: column;
}

.table-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1.5fr;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doctor-details {
  display: flex;
  flex-direction: column;
}

.doctor-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 2px;
}

.doctor-title {
  font-size: 12px;
  color: #6c757d;
}

.report-count {
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
}

.completion-rate {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rate-text {
  font-size: 12px;
  color: #6c757d;
  min-width: 35px;
}

/* 异常统计 */
.abnormal-stats {
  height: 300px;
  overflow-y: auto;
}

.abnormal-overview {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.abnormal-item {
  flex: 1;
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.abnormal-item.high {
  background: #fef0f0;
  border-color: #f56c6c;
}

.abnormal-item.low {
  background: #fdf6ec;
  border-color: #e6a23c;
}

.abnormal-item.abnormal {
  background: #fef0f0;
  border-color: #f56c6c;
}

.abnormal-label {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
}

.abnormal-count {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.abnormal-categories h4 {
  font-size: 14px;
  color: #2c3e50;
  margin-bottom: 12px;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.category-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.category-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-name {
  font-size: 13px;
  color: #2c3e50;
}

.category-count {
  font-size: 12px;
  color: #6c757d;
}

.category-bar {
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.category-progress {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #67c23a);
  transition: width 0.3s ease;
}

/* 数据表格 */
.data-table-card {
  border: 1px solid #e4e7ed;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-danger {
  color: #f56c6c;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .report-statistics-dialog {
    width: 95% !important;
  }
  
  .report-statistics-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-card {
    padding: 16px;
    gap: 12px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .doctor-stats,
  .abnormal-stats {
    height: 250px;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1.5fr 1fr 1fr;
    gap: 8px;
  }
  
  .abnormal-overview {
    flex-direction: column;
    gap: 8px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .trend-data {
    gap: 8px;
  }
  
  .trend-item {
    min-width: 50px;
    padding: 6px;
  }
  
  .doctor-info {
    gap: 8px;
  }
  
  .completion-rate {
    flex-direction: column;
    gap: 4px;
  }
}
</style>